package com.hlkj.baojin.dao.repository;

import com.hlkj.baojin.constant.BaseRepository;
import com.hlkj.baojin.constant.BaojinConstant;
import com.hlkj.baojin.entity.EarlyAlarmRecord;
import com.hlkj.baojin.entity.dto.AlarmSearch;
import com.hlkj.baojin.entity.dto.ModelList;
import com.hlkj.baojin.utils.ErrororUtil;
import com.hlkj.baojin.utils.bean.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class EarlyAlarmRecordRepository extends BaseRepository<EarlyAlarmRecord> {

    public EarlyAlarmRecordRepository(MongoTemplate mongoTemplate) {
        super(mongoTemplate);
    }

    public ModelList<EarlyAlarmRecord> listEarlyAlarmRecord(String companyId, AlarmSearch alarmSearch, List<String> companyIds, List<String> deviceIds, Page page) {
        Query query = new Query();

        query.addCriteria(Criteria.where("delete").is(BaojinConstant.IS_NO_DELETE));

        if(companyId != null){
            query.addCriteria(Criteria.where("companyId").is(companyId));
        }

        query.addCriteria(new Criteria().orOperator(
                Criteria.where("companyId").in(companyIds),
                Criteria.where("deviceId").in(deviceIds)
        ));

        if(alarmSearch.getTimeEnd() != null && alarmSearch.getTimeStart() != null){
            query.addCriteria(Criteria.where("createTime").gte(alarmSearch.getTimeStart()).lte(alarmSearch.getTimeEnd()));
        }

        query.with(new Sort(Sort.Direction.DESC, "createTime"));
        query.with(new Page(page.getPage(), page.getSize()));

        List<EarlyAlarmRecord> earlyAlarmRecordList = mongoTemplate.find(query, EarlyAlarmRecord.class);
        long count = mongoTemplate.count(query, EarlyAlarmRecord.class);

        ModelList<EarlyAlarmRecord> earlyAlarmRecordModelList = new ModelList<>(earlyAlarmRecordList, count);

        //TODO
        return earlyAlarmRecordModelList;
    }

    /**
     * type 0:公司id删除 1.设备id删除
     * @param id
     * @param type
     */
    public void deleteEarlyAlarmRecord(String id, Integer type) {

        Query query = new Query();
        query.addCriteria(Criteria.where("delete").is(BaojinConstant.IS_NO_DELETE));
        if(type.equals(0)) {
            query.addCriteria(Criteria.where("companyId").is(id));
        } else if(type.equals(1)){
            query.addCriteria(Criteria.where("deviceId").is(id));
        } else {
            ErrororUtil.isError("报警记录", "数据异常");
        }

        Update update = new Update();
        update.set("delete", BaojinConstant.IS_DELETE);

        mongoTemplate.updateMulti(query, update, EarlyAlarmRecord.class);

    }
}
